package com.example.callback;

import com.example.util.CommonUtils;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;

public class ThenApplyAsyncDemo {
    public static void main(String[] args) {
        CommonUtils.printThreadLog("main start");

        CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> {
            CommonUtils.printThreadLog("读文件，开始");
            String filterWordsContent = CommonUtils.readFile("filter_words.txt");
            CommonUtils.sleepSecond(1);
            CommonUtils.printThreadLog(filterWordsContent);
            CommonUtils.printThreadLog("读文件，结束");
            return filterWordsContent;
        });


        CompletableFuture<String[]> filterWordsFuture = readFileFuture.thenApplyAsync(content -> {
            CommonUtils.printThreadLog("转换为数组文件，开始");
            String[] filterWords = content.split(",");
            CommonUtils.sleepSecond(1);
            CommonUtils.printThreadLog("转换为数组文件，结束");
            return filterWords;
        });

        CompletableFuture<String[]> filterWordsFuture2 = readFileFuture.thenApplyAsync(content -> {
            CommonUtils.printThreadLog("转换为数组文件2，开始");
            String[] filterWords = content.split(",");
            CommonUtils.sleepSecond(2);
            CommonUtils.printThreadLog("转换为数组文件2，结束");
            return filterWords;
        });

        CompletableFuture<Void> future = CompletableFuture.allOf(filterWordsFuture, filterWordsFuture2).thenRun(() -> {
            CommonUtils.printThreadLog("两个filterWordsFuture都执行完了！");
            CommonUtils.printThreadLog("打印敏感词数据：");
            CommonUtils.printThreadLog("filterWordsFuture：" + Arrays.toString(filterWordsFuture.join()));
            CommonUtils.printThreadLog("filterWordsFuture2：" + Arrays.toString(filterWordsFuture2.join()));
        });

        CommonUtils.printThreadLog("main continue");
        future.join();
        CommonUtils.printThreadLog("main end");
    }
}
